package model

import (
	"gitee.com/lllgo/gopkg/csv"
	"gitee.com/lllgo/gopkg/utils"
	"gitee.com/lllgo/opsctl/pkg/conf"
	"os"
	"path/filepath"
)

var (
	logTable *csv.Table
	tagTable *csv.Table

	isInit = false
	dbDir  string
)

func Init() {
	dbDir = utils.GetDefString(conf.C.DBDir, "testdata")
	_ = os.MkdirAll(dbDir, os.ModePerm)

	logTable = getTable("log", func(r csv.Record, m csv.Meta) []string {
		tmp := r.(Log)
		return []string{tmp.Cmd, tmp.Err, tmp.CreatedAt}
	}, func(v []string, m csv.Meta) csv.Record {
		return Log{Cmd: v[0], Err: v[1], CreatedAt: v[2], Id: m.Id}
	})

	tagTable = getTable("tag", func(r csv.Record, m csv.Meta) []string {
		tmp := r.(Tag)
		return []string{tmp.IP, tmp.Name, tmp.Tags}
	}, func(v []string, m csv.Meta) csv.Record {
		return Tag{IP: v[0], Name: v[1], Tags: v[2]}
	})

	isInit = true
}

func HasDB() bool {
	return isInit
}

func getTable(filename string, f1 csv.RecordToCsvFunc, f2 csv.CsvSliceToRecordFunc) *csv.Table {
	t := csv.NewTable(filepath.Join(dbDir, filename+".csv"), f1, f2)
	t.StartRow = 0
	_ = t.Read()
	return t
}
